/*
Copyright (C) 2009-2011 Xanadu Development Team

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "Fame.h"
#include "../tools/MySQLM.h"
#include "Player.h"

int Fame::canFame(Player *player, int to) {
	if (player->getLevel() < 15)
		return 2;
	int from = player->getID();
	if (getLastFameLog(from))
		return 3;
	if (getLastFameSPLog(from, to))
		return 4;
	return 0;
}

void Fame::addFameLog(int from, int to) {
	mysqlpp::Connection::thread_start();
	mysqlpp::Connection* conn = MySQL::getInstance()->getPool()->grab();
	mysqlpp::Query query = conn->query();
	query << "INSERT INTO fame_log (`from`, `to`, `time`) VALUES (" << from << "," << to << ", NOW())";
	query.execute();
	MySQL::getInstance()->getPool()->release(conn);
	mysqlpp::Connection::thread_end();
}

bool Fame::getLastFameLog(int from) { // Last fame from player
	mysqlpp::Connection::thread_start();
	mysqlpp::Connection* conn = MySQL::getInstance()->getPool()->grab();
	mysqlpp::Query query = conn->query();
	query << "SELECT `time` FROM `fame_log` WHERE `from`=" << from << " AND UNIX_TIMESTAMP(`time`) > UNIX_TIMESTAMP()-86400 ORDER BY `time` DESC LIMIT 1";
	mysqlpp::StoreQueryResult res = query.store();
	MySQL::getInstance()->getPool()->release(conn);
	mysqlpp::Connection::thread_end();
	if (!res.empty()) {
		return (res.num_rows() != 0);
	}
	return false;
}

bool Fame::getLastFameSPLog(int from, int to) {
	mysqlpp::Connection::thread_start();
	mysqlpp::Connection* conn = MySQL::getInstance()->getPool()->grab();
	mysqlpp::Query query = conn->query();
	query << "SELECT `time` FROM `fame_log` WHERE `from`=" << from << " AND `to`=" << to << " AND UNIX_TIMESTAMP(`time`) > UNIX_TIMESTAMP()-2592000 ORDER BY `time` DESC LIMIT 1";
	mysqlpp::StoreQueryResult res = query.store();
	MySQL::getInstance()->getPool()->release(conn);
	mysqlpp::Connection::thread_end();
	if (!res.empty()) {
		return (res.num_rows() != 0);
	}
	return false;
}